package com.lc.pianostudent.view;


import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.lc.pianostudent.BaseApplication;
import com.lc.pianostudent.R;
import com.lc.pianostudent.activity.ContactDetailActivity;
import com.lc.pianostudent.activity.TeacherDetailActivity;
import com.lc.pianostudent.bean.CommentsBean;
import com.lc.pianostudent.spannable.CircleMovementMethod;
import com.lc.pianostudent.spannable.SpannableClickable;
import com.lc.pianostudent.util.DisplayUtils;
import com.lc.pianostudent.util.UrlUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * =======================================================
 * project:CircleFriend
 * copyright：Copyright (C) 2017 SHANXI XIAN Technologies Ltd
 * author：xszhang
 * date：created by 2017/11/4 13:40
 * version：V1.0
 * descript：自定义评论view
 * =======================================================
 */
public class CommentListView extends LinearLayout {
    private List<CommentsBean> mDatas;
    private int itemColor;
    private float mTextSize;
    private int itemSelectorColor;
    private OnItemClickListener onItemClickListener;
    private OnItemLongClickListener onItemLongClickListener;
    private LayoutInflater layoutInflater;
    private Context context;
    private String name;

    public void setDatas(List<CommentsBean> datas) {
        if (datas == null) {
            datas = new ArrayList<CommentsBean>();
        }
        mDatas = datas;
        notifyDataSetChanged();
    }

    public OnItemClickListener getOnItemClickListener() {
        return onItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public OnItemLongClickListener getOnItemLongClickListener() {
        return onItemLongClickListener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    public List<CommentsBean> getDatas() {
        return mDatas;
    }

    public CommentListView(Context context) {
        super(context);
        this.context = context;
    }

    public CommentListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        int width = getScreenWidth();
        initAttrs(attrs,context,width);
    }

    public CommentListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        int width = getScreenWidth();
        initAttrs(attrs,context,width);
    }


    protected void initAttrs(AttributeSet attrs,Context context,int width) {
        Log.e("====",width+"===");
        TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.PraiseListView, 0, 0);
        try {
            //textview的默认颜色
            itemColor = typedArray.getColor(R.styleable.PraiseListView_item_color,Color.parseColor("#604300"));
            if(width == 720){
                mTextSize = typedArray.getDimensionPixelSize(R.styleable.PraiseListView_text_size, width/40);

            }else if(width  == 768){
                mTextSize = typedArray.getDimensionPixelSize(R.styleable.PraiseListView_text_size, width/50);

            }else if(width > 768  && width <= 1080){
                mTextSize = typedArray.getDimensionPixelSize(R.styleable.PraiseListView_text_size, width/80);

            }else if(width <720){
                mTextSize = typedArray.getDimensionPixelSize(R.styleable.PraiseListView_text_size, width/40);

            }else if(width >1080){
                mTextSize = typedArray.getDimensionPixelSize(R.styleable.PraiseListView_text_size, width/90);

            }
            itemSelectorColor = typedArray.getColor(R.styleable.PraiseListView_item_selector_color, getResources().getColor(R.color.praise_item_selector_default));

        } finally {
            typedArray.recycle();
        }
    }

    public void notifyDataSetChanged() {
        removeAllViews();
        if (mDatas == null || mDatas.size() == 0) {
            return;
        }
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < mDatas.size(); i++) {
            final int index = i;
            View view = getView(index);
            if (view == null) {
                throw new NullPointerException("listview item layout is null, please check getView()...");
            }
            addView(view, index, layoutParams);
        }
    }

    private View getView(final int position) {
        if (layoutInflater == null) {
            layoutInflater = LayoutInflater.from(getContext());
        }
        View convertView = layoutInflater.inflate(R.layout.comment_item_layout, null, false);
        TextView commentTv = (TextView) convertView.findViewById(R.id.comment_sender);
        commentTv.setTextSize(mTextSize);
        final CircleMovementMethod circleMovementMethod = new CircleMovementMethod(itemSelectorColor, itemSelectorColor);

        final CommentsBean bean = mDatas.get(position);
        if(String.valueOf(bean.getUserid()).equals(BaseApplication.BasePreferences.readTeacherId())){
            name = BaseApplication.BasePreferences.readTeacherName().substring(0,1)+"老师";
        }else {
            if(!TextUtils.isEmpty(bean.getName())){
                name = bean.getName();
            }else {
                name = "null";
            }

        }

        String id = String.valueOf(bean.getUserid());
        String toReplyName = "";
        if (bean.getFromname() != null) {
            if(String.valueOf(bean.getFromuserid()).equals(BaseApplication.BasePreferences.readTeacherId())){
                toReplyName = BaseApplication.BasePreferences.readTeacherName().substring(0,1)+"老师";
            }else {
//                toReplyName = bean.getFromname();
                if(!TextUtils.isEmpty(bean.getFromname())){
                    toReplyName = bean.getFromname();
                }
//                else {
//                    toReplyName = "null";
//                }

            }
//            toReplyName = bean.getFromname();
        }
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(setClickableSpan(name, id));

        if (!TextUtils.isEmpty(toReplyName)) {
            builder.append(" 回复 ");
//            builder.append(setClickableSpan(toReplyName, bean.getId());
            builder.append(setClickableSpan(toReplyName, bean.getFromuserid()));
        }
        builder.append(": ");
        //转换表情字符
        String contentBodyStr = bean.getContent();
        builder.append(UrlUtils.formatUrlString(contentBodyStr));
        commentTv.setText(builder);

        commentTv.setMovementMethod(circleMovementMethod);
        commentTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (circleMovementMethod.isPassToTv()) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemClick(position);
                    }
                }
            }
        });
        commentTv.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (circleMovementMethod.isPassToTv()) {
                    if (onItemLongClickListener != null) {
                        onItemLongClickListener.onItemLongClick(position);
                    }
                    return true;
                }
                return false;
            }
        });

        return convertView;
    }

    @NonNull
    private SpannableString setClickableSpan(final String textStr, final String id) {
        SpannableString subjectSpanText = new SpannableString(textStr);
        subjectSpanText.setSpan(new SpannableClickable(itemColor) {
                                    @Override
                                    public void onClick(View widget) {
//                                        Toast.makeText(BaseApplication.getContext(), textStr + " &id = " + id, Toast.LENGTH_SHORT).show();
                                        if( id.equals(BaseApplication.BasePreferences.readUID())){
                                            context.startActivity(new Intent(context, ContactDetailActivity.class).putExtra("id",id).putExtra("type","0"));
                                        } else if( id.equals(BaseApplication.BasePreferences.readTeacherId())){
                                            context.startActivity(new Intent(context, TeacherDetailActivity.class).putExtra("id",id).putExtra("type","1"));
                                        }else {
                                           context.startActivity(new Intent(context, ContactDetailActivity.class).putExtra("id",id).putExtra("type","1"));

                                        }

                                    }
                                }, 0, subjectSpanText.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return subjectSpanText;
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public interface OnItemLongClickListener {
        void onItemLongClick(int position);
    }

    private int getScreenWidth() {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}
